import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { getTokenInfo } from '@/utils/storage'

type Message = {
  type: 'robot' | 'user'
  msg: string
  timestamp: number
}

export default function ProfileChat() {
  const [msg, setMsg] = useState('')

  const [list, setList] = useState<Message[]>([])

  const handleSend = () => {
    if (!msg.trim()) return
    const userMsg: Message = { type: 'user', msg, timestamp: Date.now() }
    setList([...list, userMsg])
    clientRef.current.emit('message', userMsg)
    setMsg('')
  }

  const handleKeyUp = (e: React.KeyboardEvent<HTMLSpanElement>) => {
    if (e.key === 'Enter') handleSend()
  }

  const clientRef = useRef<any>(null)

  useEffect(() => {
    const socket = io(baseURL, {
      query: { token: getTokenInfo().token },
      transports: ['websocket'],
    })

    clientRef.current = socket

    socket.on('connect', () => {
      setList([
        {
          type: 'robot',
          msg: '亲爱的用户您好，小智同学为您服务。',
          timestamp: Date.now(),
        },
        { type: 'user', msg: '你好啊。', timestamp: Date.now() + 1 },
      ])
    })

    socket.on('message', (data) => {
      console.log(data)
      setList((oldList) => [...oldList, { type: 'robot', ...data }])
    })

    return () => {
      socket.close()
    }
  }, [])

  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    })
  }, [list])

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 - 开始 */}
      <div className="chat-list">
        {list.map((item) => {
          return item.type === 'robot' ? (
            <div key={item.timestamp} className="chat-item robot">
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{item.msg}</div>
            </div>
          ) : (
            <div key={item.timestamp} className="chat-item user">
              <img
                src={'http://toutiao.itheima.net/images/user_head.jpg'}
                alt=""
              />
              <div className="message">{item.msg}</div>
            </div>
          )
        })}
      </div>
      {/* 聊天记录列表 - 结束 */}

      {/* 底部消息输入框 */}
      <div className="footer">
        <div className="input-footer">
          <Icon type="iconbianji" />
          <Input
            autoFocus
            value={msg}
            className="no-border"
            placeholder="请描述您的问题"
            onChange={(e) => setMsg(e.target.value)}
            onKeyUp={(e) => handleKeyUp(e)}
          />
          <span className="send" onClick={handleSend}>
            发送
          </span>
        </div>
      </div>
    </div>
  )
}
